from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QLabel, QLineEdit,
    QPushButton, QMessageBox, QComboBox, QHBoxLayout
)

class LoginWindow(QWidget):
    def __init__(self, auth_manager, parent=None):
        super().__init__(parent)
        self.auth_manager = auth_manager
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignCenter)
        # 界面元素
        self.username_input = QLineEdit(placeholderText="请输入用户名")
        self.password_input = QLineEdit(placeholderText="请输入密码", echoMode=QLineEdit.Password)
        login_btn = QPushButton("登录", clicked=self.on_login)
        register_btn = QPushButton("立即注册", clicked=lambda: self.parent().setCurrentIndex(1))
        change_pw_btn = QPushButton("修改密码", clicked=lambda: self.parent().setCurrentIndex(2))
        # 布局管理
        layout.addWidget(QLabel("康复系统登录"))
        layout.addSpacing(20)
        layout.addWidget(self.username_input)
        layout.addWidget(self.password_input)
        layout.addWidget(login_btn)
        # 底部按钮布局
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(register_btn)
        bottom_layout.addWidget(change_pw_btn)
        layout.addLayout(bottom_layout)
        self.setLayout(layout)

    def on_login(self):
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()
        if not username or not password:
            QMessageBox.warning(self, "输入错误", "用户名和密码不能为空")
            return
        result = self.auth_manager.handle_login(username, password)
        # 处理返回结果
        if isinstance(result, tuple) and len(result) == 2:
            success, data = result
            if success:
                # 成功登录，data应该是用户信息字典
                if isinstance(data, dict):
                    self.parent().parent().show_main_menu(data)
                else:
                    # 如果data不是字典，尝试获取用户信息
                    user_info = self.auth_manager.get_user_info(username)
                    if isinstance(user_info, dict):
                        self.parent().parent().show_main_menu(user_info)
                    else:
                        QMessageBox.warning(self, "登录失败", "无法获取用户信息")
            else:
                # 登录失败，data是错误消息
                error_msg = data if isinstance(data, str) else "登录失败"
                QMessageBox.warning(self, "登录失败", error_msg)
        else:
            # 处理非标准返回值
            QMessageBox.warning(self, "登录失败", "系统返回了意外的响应格式")


class RegisterWindow(QWidget):
    def __init__(self, auth_manager, parent=None):
        super().__init__(parent)
        self.auth_manager = auth_manager
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignCenter)
        # 角色映射 - 显示中文但存储英文
        self.role_mapping = {
            '医生': 'doctor',
            '治疗师': 'therapist',
            '患者': 'patient'
        }
        # 界面元素
        self.username_input = QLineEdit(placeholderText="设置用户名")
        self.password_input = QLineEdit(placeholderText="设置密码", echoMode=QLineEdit.Password)
        self.confirm_pw_input = QLineEdit(placeholderText="确认密码", echoMode=QLineEdit.Password)
        self.role_combo = QComboBox()
        self.role_combo.addItems(self.role_mapping.keys())  # 添加中文显示
        register_btn = QPushButton("注册", clicked=self.on_register)
        back_btn = QPushButton("返回登录", clicked=lambda: self.parent().setCurrentIndex(0))
        # 布局管理
        layout.addWidget(QLabel("用户注册", styleSheet="font-size: 18px;"))
        layout.addSpacing(15)
        layout.addWidget(self.username_input)
        layout.addWidget(self.password_input)
        layout.addWidget(self.confirm_pw_input)
        layout.addWidget(QLabel("选择角色:"))
        layout.addWidget(self.role_combo)
        layout.addWidget(register_btn)
        layout.addWidget(back_btn)
        self.setLayout(layout)

    def on_register(self):
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()
        confirm_pw = self.confirm_pw_input.text().strip()
        # 获取选择的角色（中文）并映射为英文
        selected_role_display = self.role_combo.currentText()
        role = self.role_mapping.get(selected_role_display, 'patient')  # 默认patient
        if not all([username, password, confirm_pw]):
            QMessageBox.warning(self, "输入错误", "所有字段必须填写")
            return
        if password != confirm_pw:
            QMessageBox.warning(self, "密码错误", "两次输入的密码不一致")
            return
        try:
            success, msg = self.auth_manager.handle_register(username, password, role)
            QMessageBox.information(self, "提示", msg)
            if success:
                self.parent().setCurrentIndex(0)  # 跳转回登录界面
        except Exception as e:
            QMessageBox.critical(self, "注册失败", f"发生错误: {str(e)}")


class ChangePasswordWindow(QWidget):
    def __init__(self, auth_manager, parent=None):
        super().__init__(parent)
        self.auth_manager = auth_manager
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignCenter)
        # 界面元素
        self.username_input = QLineEdit(placeholderText="用户名")
        self.old_pw_input = QLineEdit(placeholderText="旧密码", echoMode=QLineEdit.Password)
        self.new_pw_input = QLineEdit(placeholderText="新密码", echoMode=QLineEdit.Password)
        self.confirm_pw_input = QLineEdit(placeholderText="确认新密码", echoMode=QLineEdit.Password)
        submit_btn = QPushButton("确认修改", clicked=self.on_change_password)
        back_btn = QPushButton("返回登录", clicked=lambda: self.parent().setCurrentIndex(0))
        # 布局管理
        layout.addWidget(QLabel("修改密码", styleSheet="font-size: 18px;"))
        layout.addSpacing(15)
        layout.addWidget(self.username_input)
        layout.addWidget(self.old_pw_input)
        layout.addWidget(self.new_pw_input)
        layout.addWidget(self.confirm_pw_input)
        layout.addWidget(submit_btn)
        layout.addWidget(back_btn)
        self.setLayout(layout)

    def on_change_password(self):
        username = self.username_input.text().strip()
        old_pw = self.old_pw_input.text().strip()
        new_pw = self.new_pw_input.text().strip()
        confirm_pw = self.confirm_pw_input.text().strip()
        if not all([username, old_pw, new_pw, confirm_pw]):
            QMessageBox.warning(self, "输入错误", "所有字段必须填写")
            return
        if old_pw == new_pw:
            QMessageBox.warning(self, "输入错误", "新旧密码相同")
            return
        if new_pw != confirm_pw:
            QMessageBox.warning(self, "密码错误", "新密码与确认密码不一致")
            return
        success, msg = self.auth_manager.handle_password_change(username, old_pw, new_pw)
        QMessageBox.information(self, "提示", msg)
        if success:
            self.parent().setCurrentIndex(0)  # 返回登录界面
